package com.wenheng.aop;

import com.wenheng.annotation.TargetDataSource;
import com.wenheng.commer.DataSourceType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import java.lang.reflect.Method;

/**
 * 面向切面切换数据库
 */
public abstract  class AbstractDataSourceAop {
    @Pointcut("@annotation(com.wenheng.annotation.TargetDataSource)")
    public void dataSourceBefore() {

    }

    //根据数据库的id直接匹配名称，若没有使用注解默认调用read数据
    @Before("dataSourceBefore()")
    public void Before(JoinPoint joinpoint){
        doDataSource(joinpoint);
    }


    //配置数据库类型
    public abstract void doDataSource(JoinPoint joinPoint);

    /**
     * 获得DataSource注解类型的type
     */
    public String getMthodTableType(JoinPoint joinPoint) {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class<?> targetClass;
        //默认是主数据源·
        String value = DataSourceType.master;
        try {
            targetClass = Class.forName(targetName);
            Method[] methods = targetClass.getMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Class<?>[] clazzs = method.getParameterTypes();
                    if (clazzs.length == arguments.length) {
                        System.out.println("注解内的值："+method.getAnnotation(TargetDataSource.class).value());
                        value = method.getAnnotation(TargetDataSource.class).value();
                        break;
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return value;
    }
}
